package org.sapmentors.returns.robot;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import org.sapmentors.returns.material.Material;
import org.sapmentors.returns.material.QueryMaterial;
import org.sapmentors.returns.service.CreateServiceRequest;

import com.google.wave.api.*;

@SuppressWarnings("serial")
public class SAPESRobotServlet extends AbstractRobotServlet {
	  private static final Logger log = Logger.getLogger("Robot");

	  private String ownname = "sap-es@appspot.com";
	  private String customerNumber = "1171";
		  
	Cache cache;
		public SAPESRobotServlet(){
			super();

	        try {
	            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
	        } catch (CacheException e) {
	            //
	        }

		}
	  
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		
		if (bundle.wasSelfAdded()) {

			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.append(ownname+ " added version " +this.getVersion() +" \n");
			
			
			textView.append("\nHi "+customerNumber+" which equiptment will you create a service request for\n");
			FormView form = textView.getFormView();
			QueryMaterial qm = new QueryMaterial();
			ArrayList<Material> list = qm.getMaterial(customerNumber);
			for(Material mat : list){
				form.append(new FormElement ( ElementType.BUTTON, mat.getId(), mat.getId(),  mat.getId()));
				textView.append(" ");
				form.append( new FormElement (ElementType.LABEL, "description"+mat.getId(), mat.getDescription()));
				textView.append(" ");
				form.append(new FormElement ( ElementType.LABEL, "id"+mat.getId(),  mat.getMaterialId()));
				textView.append("\n");
				cache.put(mat.getId(), mat);
			}
			
			textView.appendMarkup("\n<a href=\"http://masteringwave.com/\">MasteringWave</a> <br />");
		}

		for (Event e : bundle.getEvents()) {
			
			if (e.getType() == EventType.FORM_BUTTON_CLICKED  && !e.getModifiedBy().equals(ownname) && !e.getModifiedBy().endsWith("@gwave.com")){
				if(e.getButtonName().equals("create")){
					//create service request and show status
					FormView currentForm = e.getBlip().getDocument().getFormView();
					String materialId = currentForm.getFormElement("id").getValue();
					String errorDescription = currentForm.getFormElement("problemText").getValue();
					CreateServiceRequest csr= new CreateServiceRequest();
					String requestID = csr.getServiceRequest(materialId,errorDescription);
					Blip statusBlip = e.getBlip().createChild();
					TextView status = statusBlip.getDocument();
					
					status.appendMarkup("Service request creted with id <b>"+ requestID +"</b> ");
					status.append("\n");
					Hashtable<String, String> statusTable = csr.getStatusResult();
					Enumeration<String> keys =  statusTable.keys();
					while (keys.hasMoreElements()) {
						String key = (String) keys.nextElement();
						status.appendMarkup("<b>"+key+"</b> : " +statusTable.get(key) );
						status.append("\n");
					}
					String[] creater = e.getModifiedBy().split("@");
					String internPerson = creater[0]+"-test@"+creater[1];
					wavelet.addParticipant(internPerson);
					
				
					
					
				}else{
					// create form for submitting service problem
					Object obj = cache.get(e.getButtonName());
					Object hasBeenSelected = cache.get(wavelet.getWaveletId() + ""+e.getButtonName() );
					if (hasBeenSelected != null){
						return;
					}
					
					cache.put(wavelet.getWaveletId() + ""+e.getButtonName(),"x" );
					Material mat = new Material();
					if (obj != null) {
						mat = (Material) obj;
					} else {
						mat.setDescription("Not found");
					}
			
					Blip blip = e.getBlip().createChild();
				
					TextView textView = blip.getDocument();
					textView.append("\nCreate the Service Request\n");
					FormView form = textView.getFormView();
					textView.append("Equipment ID  ");
					form.append(new FormElement(ElementType.INPUT,
									"id",  e.getButtonName()));
					textView.append("\nEquipment Description  ");
					form.append(new FormElement(ElementType.LABEL,"description", mat.getDescription()));
					textView.append("\nProblem Statement  ");
					form.append(new FormElement(ElementType.INPUT, "problemText", ""));
					textView.append("\nCreate ");
					form.append(new FormElement(ElementType.BUTTON, "create",
										"create", "Create"));
					
				}
			}
			

		}

	}


}